package com.rfsp.common.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.rfp.sm.utils.SM3Utils;
import com.rfp.ws.utils.ECCUtils;
import com.rfsp.common.base.BaseController;
import com.rfsp.common.pojo.dto.LoginDTO;
import com.rfsp.common.pojo.po.LoginPO;
import com.rfsp.common.pojo.po.UserPO;
import com.rfsp.common.service.*;
import com.rfsp.common.util.JsonUtil;
import com.rfsp.common.util.ValidUtil;
import com.rfsp.mcp.service.RecordService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;


@Profile("dev")
@Controller
public class DevController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(DevController.class);
	
	@Autowired
	UserService userService;
	
	@Autowired
	LoginController loginController;
	@Autowired
	DefaultKaptcha  captcha;


	@RequestMapping("/")
	public ModelAndView index(ModelMap model) {

		return new ModelAndView("/index");
	}


	@PostMapping("/login/login")
	public ModelAndView login(@Valid LoginDTO loginDto, ModelMap model, BindingResult br, HttpServletRequest request) {
//		if(br.hasreturn loginController.errors()) {
//			return br.getAllreturn loginController.errors().get(0).getDefaultMessage();
//		}
		
//		if("0".equals(paramService.getCacheValue(ParamCache.ENV))) {
//			return redirectView("/return loginController.error/notLogin");
//		}
		
		String userCode  = loginDto.getUserCode();
		String password1 = loginDto.getPassword();
		String password  = loginDto.getPasswordMd5();
		String sessionVcode = (String) request.getSession().getAttribute("vcode");
		String vcode = loginDto.getVcode();
		
		if(ValidUtil.isEmpty(userCode)) {
			return loginController.error(model,"请输入用户名");
		} else if(ValidUtil.isEmpty(password1) ) {
			return loginController.error(model,"请输入密码");
		} else if(ValidUtil.isEmpty(password)) {
			return loginController.error(model,"密码不能为空");
		} else if(StringUtils.isEmpty(vcode)) {
			return loginController.error(model,"请输入验证码");
		} else if(!vcode.equals(sessionVcode)) {
			return loginController.error(model,"验证码错误");
		}
		
		password = loginController.getP(password).toUpperCase();
		password = SM3Utils.toHashUpperCase(password, 32);

		UserPO user = userService.getUserByUserCodeAndPwd(userCode, password);
		if(user == null) return loginController.errorLogin(model);
		return loginController.loginInit(request, model, user, password, "0", UUID.randomUUID().toString(), vcode);
	}


	/**
	 * 生成验证码图片
	 */
	@GetMapping(value = "/captcha")
	public void captcha(HttpSession session, HttpServletResponse response) throws Exception {
//		CircleCaptcha//圆圈干扰ShearCaptcha//扭曲干扰LineCaptcha //线条干扰
		ICaptcha captcha = CaptchaUtil.createLineCaptcha(80, 30, 4, 1);
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		try {
			String vcode = captcha.getCode();
			vcode = "1111";
			session.setAttribute("vcode", vcode);
			captcha.write(response.getOutputStream());
			response.getOutputStream().close();
		} catch (IOException e) {

			throw new RuntimeException(e);

		}
	}


	/**
	 * 生成验证码图片
	 */
	//@GetMapping(value = "/captcha")
	public void captcha2(HttpSession session, HttpServletResponse response) throws Exception {
		//生成
		String code = captcha.createText();
		code = "1111";
		//保存到Session
		session.setAttribute("vcode", code);
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		BufferedImage image = captcha.createImage(code);
		try (ServletOutputStream out = response.getOutputStream()) {
			ImageIO.write(image, "jpg", out);
			out.flush();
		}
	}
}
